package cn.itcast.mobilebrowser.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.itcast.mobilebrowser.R;

import cn.itcast.mobilebrowser.adapter.HistoryAdapter;

import cn.itcast.mobilebrowser.model.History;

import cn.itcast.mobilebrowser.viewmodel.HistoryViewModel;

public class HistoryFragment extends Fragment {

    private final String TAG = "HistoryFragment";

    private static final String ARG_SECTION_NUMBER = "section_number";

    private HistoryViewModel historyViewModel;
    private List<History> historyList;

    private HistoryAdapter historyAdapter;
    private ListView listView;
    private ImageView deleteAllHistory;

    public HistoryFragment() {
        // Required empty public constructor
    }


    public static HistoryFragment newInstance(int index) {
        HistoryFragment fragment = new HistoryFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, index);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        int index = 1;
        if (getArguments() != null) {
            index = getArguments().getInt(ARG_SECTION_NUMBER);
        }
        Log.d(TAG, "当前Fragment：" + index);

        // 测试数据初始化，生成东西放在test_data中
        this.initData();

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View root = inflater.inflate(R.layout.fragment_history, container, false);

        listView = root.findViewById(R.id.history);
        deleteAllHistory = root.findViewById(R.id.delete_all_history);

        this.initView();

        return root;
    }

    private void initView() {
        // 初始化适配器
        historyAdapter = new HistoryAdapter(requireActivity(), R.layout.web_item_time, historyList);

        // 将适配器上的数据传递给listView,在activity_book_marks.xml中
        listView.setAdapter(historyAdapter);

        // 为ListView注册一个监听器，当用户点击了ListView中的任何一个子项时，就会回调onItemClick()方法
        // 在这个方法中可以通过position参数判断出用户点击的是那一个子项
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                History history = historyList.get(position);
                Log.d(TAG, history.getUrl());
                Toast.makeText(requireActivity(),"进入" + history.getTitle(),Toast.LENGTH_SHORT).show();

                // 点击后传回链接给网页，requireAc 获取父activity，为它intent设置返回值
                Intent intent = new Intent();
                intent.putExtra("url", history.getUrl());
                requireActivity().setResult(Activity.RESULT_OK, intent);
                requireActivity().finish();
            }
        });

        // 设置长按事件
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                // 生成popup菜单
                PopupMenu popupMenu = new PopupMenu(getContext(), view);
                popupMenu.getMenuInflater().inflate(R.menu.pop_menu_delete, popupMenu.getMenu());
                // 设置菜单点击事件
                popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        // 拿到要删除的对象
                        History history = (History) listView.getItemAtPosition(position);
                        historyViewModel.delete(history);
                        return false;
                    }
                });
                // 显示菜单
                popupMenu.setGravity(Gravity.END);
                popupMenu.show();
                // 返回true屏蔽点击事件
                return true;
            }
        });

        // 删除全部
        deleteAllHistory.setOnClickListener(v -> {
            // 弹出确认对话框
            AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
            builder.setMessage(R.string.delete_all_history)
                    .setPositiveButton(R.string.confirm, (dialog, which) -> {
                        historyViewModel.deleteAllHistory();
                    })
                    .setNegativeButton(R.string.cancel, (dialog, which) -> {
                        // 取消删除
                    });
            builder.create().show();
        });
    }

    /**
     * 初始化数据以装填至列表
     */
    private void initData() {
        historyList = new ArrayList<>();
        // 初始化ViewModel
        historyViewModel = new ViewModelProvider(requireActivity()).get(HistoryViewModel.class);

        // 观察书签表的数据，一旦数据有改动就更新list的数据
        // 此处的改动是指数据库数据被更新：增删改
        historyViewModel.getAllHistory().observe(requireActivity(), new Observer<List<History>>() {
            @Override
            public void onChanged(List<History> history) {
                historyList.clear();
                historyList.addAll(history);
                // 通知适配器数据修改
                historyAdapter.notifyDataSetChanged();
            }
        });

        // 用于测试的初始数据，第一次安装才用，之后记得注释再跑一次避免重复添加
        // this.addTestData();
    }

    private void addTestData() {
        Date date = new Date();
        History history1 = new History("百度", "https://www.baidu.com/", date);
        historyViewModel.insert(history1);
        History history2 = new History("字节跳动", "https://bytedance.com/zh/",date);
        historyViewModel.insert(history2);
        History history3 = new History("哔哩哔哩", "https://www.bilibili.com/", date);
        historyViewModel.insert(history3);
        History history4 = new History("必应", "https://www.bing.com/", date);
        historyViewModel.insert(history4);
    }

}